import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { format, subDays } from 'date-fns';

import { defalutImg } from '../../../../comm';
import { CommonService } from '../../../../services-common/common.service';
import { LuckDrawManageService } from '../luck-draw-manage.service';

@Component({
  selector: 'app-love-luckdraw-edit',
  templateUrl: './love-luckdraw-edit.component.html',
  styleUrls: ['./love-luckdraw-edit.component.scss']
})
export class LoveLuckdrawEditComponent implements OnInit {

  formWidth = '100px';
  fallback: string = defalutImg;
  routeParams: any = {};
  /**
   * 时间段选择 前后限制
   * ----------------------------------------------------------------
   */
  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.formParams.endTime) {
      return false;
    }
    return startValue.getTime() > new Date(this.formParams.endTime).getTime();
  };
  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.formParams.beginTime) {
      return false;
    }
    return endValue.getTime() <= new Date(this.formParams.beginTime).getTime();
  };

  formParams: any = {
    status: 0,
    raffleLimit: '', // 抽奖限制 0 需要登录 1不需要登录
    activityName: '', // 活动名称
    beginTime: '', // 活动开始时间
    endTime: '', // 活动结束时间
    bak: '' // 备注
  };
  // 奖品类型 1-回收成交加价、2-配件优惠券 、3-二手优惠券、4-谢谢惠顾
  prizeTypeOptions = [
    {value: 1, label: '回收成交加价'},
    {value: 2, label: '配件优惠券'},
    {value: 3, label: '二手优惠券'},
    {value: 4, label: '谢谢惠顾'}
  ];
  submitLoading = false;

  /**
   * 奖品配置
   * ----------------------------------------------------------------
   */
  tableConfigData: any = [
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: '', isThank: 0, name: '', clew: '', imgUrl: '', couponNo: '', price: '', probability: '', stock: ''},
    {type: 4, isThank: 1, name: '谢谢参与', clew: '我知道了', imgUrl: '', couponNo: '', price: '', probability: '', stock: '0'}
  ];

  // 默认文字设置
  defaultSetArrs = [
    {id: 1, name: '回收成交+X元', clew: '奖品需订单成交后一起发放哦~'},
    {id: 2, name: '', clew: '奖品可在我的优惠券中查看并使用哦~'},
    {id: 4, name: '谢谢参与', clew: '我知道了'}
  ];

  constructor(
    private msg: NzMessageService,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private services: LuckDrawManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit(): void {
    if (this.routeParams.id) {
      this.loadDetatilsData();
    }
  }

  // 详情
  async loadDetatilsData() {
    let params = {
      id: this.routeParams.id
    }
    const msgId = this.msg.loading('数据加载中...', {nzDuration: 0}).messageId;
    const {code, data, message}: any = await this.services.getLoveLuckDrawDetailsData(params);
    this.msg.remove(msgId);

    if (code === 0) {
      const {activity, list} = data || {};
      // 基础信息
      for (let key in this.formParams) {
        this.formParams[key] = !this.commonService.isEmpty(activity[key]) ? activity[key] : '';
      }
      // 复制设置状态未开始 status == 0
      if (this.routeParams.type === 2) {
        this.formParams.status = 0;
      }

      // 奖品配置
      this.tableConfigData = list;
    }
  }

  /**
   * 奖品类型选择 1-回收成交加价、2-配件优惠券 、3-二手优惠券、4-谢谢惠顾
   * @param val 
   * @param index 
   */
  prizeTypeChange(val: any, index: number) {
    // set default text
    if ([1, 2].includes(val)) {
      let obj = this.defaultSetArrs.find(el => el.id === val);
      this.tableConfigData[index].name = obj?.name;
      this.tableConfigData[index].clew = obj?.clew;
    }

    this.tableConfigData[index].couponNo = '';
    this.tableConfigData[index].price = '';
  }

  // 保存
  async submitFormData() {
    if (!this.validateData()) {
      return
    }

    let params: any = {
      activity: {
        ...this.formParams
      },
      activityPrizeList: this.tableConfigData
    }
    if (this.routeParams.type == 1 && this.routeParams.id) {
      params.activity.id = this.routeParams.id;
    }

    // return
    this.submitLoading = true;
    const {code, data, message}: any = await this.services.modifyLoveLuckDrawData(params);
    this.submitLoading = false;

    if (code === 0) {
      this.msg.success('保存成功');
      this.routeBack();
    }
  }

  validateData() {
    // 奖品参数
    const isPrizeEmpty = this.tableConfigData
                          .filter((el: any) => el.type !== 4)
                          .some((tag: any) => (tag.type === 1 && this.commonService.isEmpty(tag.price)) || (tag.type !== 1 && this.commonService.isEmpty(tag.couponNo)));

    if (this.commonService.isEmpty(this.formParams.raffleLimit)) {
      this.msg.warning('请选择抽奖限制');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.activityName)) {
      this.msg.warning('请输入活动名称');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.beginTime)) {
      this.msg.warning('请选择开始时间');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.endTime)) {
      this.msg.warning('请选择结束时间');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.endTime)) {
      this.msg.warning('请选择结束时间');
      return false;
    } else if (this.validateConfigData('type')) {
      this.msg.warning('奖品配置：奖品类型存在未选项!');
      return false;
    } else if (this.validateConfigData('name')) {
      this.msg.warning('奖品配置：奖品名称存在未填写项!');
      return false;
    } else if (this.validateConfigData('clew')) {
      this.msg.warning('奖品配置：中奖提示语存在未填写项!');
      return false;
    } else if (this.validateConfigData('imgUrl')) {
      this.msg.warning('奖品配置：图标存在未上传项!');
      return false;
    } else if (isPrizeEmpty) {
      this.msg.warning('奖品配置：奖品参数存在未填写项!');
      return false;
    } else if (this.validateConfigData('probability', true)) {
      this.msg.warning('奖品配置：中奖概率存在未填写项!');
      return false;
    } else if (this.getProbabilityTotal() > 100) {
      this.msg.warning('奖品配置：奖品总概率不能超过100%!');
      return false;
    } else if (this.validateConfigData('stock', true)) {
      this.msg.warning('奖品配置：每日发放总数量存在未填写项!');
      return false;
    } else {
      return true;
    }
  }

  validateConfigData(verifField: string, isThanks?:boolean) {
    let validateArrs = isThanks ? this.tableConfigData.filter((el: any) => el.type !== 4) : this.tableConfigData;
    return validateArrs.some((item: any) => {
      return this.commonService.isEmpty(item[verifField]);
    });
  }

  // 清除
  clearItemData(item: any, index: number) {
    Object.keys(item).forEach(key => {
      this.tableConfigData[index][key] = '';
    })
  }

  // 拖拽排序
  drop(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.tableConfigData, event.previousIndex, event.currentIndex);
  }

  // 时间Change
  timeChange(val: any, key: string) {
    this.formParams[key] = val ? format(new Date(val), 'yyyy-MM-dd HH:mm:ss') : '';
  }

  /**
   * 抽奖限制Change
   * 不需要登录时，点击抽奖无需登录，但是下方奖品类型只能配置回收成交加价
   * @param val 
   * ----------------------------------------------------------------
   */
  drawTypeChange(val: any) {
    if (val === 1) {
      this.tableConfigData.forEach((item: any, index: number) => {
        if (![1, 4].includes(item.type)) {
          this.clearItemData(item, index);
        }
      })
    }
  }

  // 概率总和
  getProbabilityTotal() {
    const arrs = this.tableConfigData.filter((el: any) => el.type !== 4);
    return arrs.reduce((total: any, item: any) => {
      return total + (Number(item.probability) || 0);
    }, 0)
  }

  routeBack() {
    history.back();
  }
}
